// index.js
// 获取应用实例
var http = require('../../script/api.js')
const app = getApp()
var config = require('../../script/config.js');

Page({
  data: {
    userinfo: null,
    interval: 4000,
    duration: 500,
    timer: null,
    msgList: [],
    multiple: 1,
    activeIndex: 1,
    loading: false,
    noData: false,
    MenuRoutes: [{
        name: '待执行',
        icon: 'order_3.png',
        url: 'todoOrder',
        MENU_ID: 390101
      },
      {
        name: '二次派单',
        icon: 'order_2.png',
        url: 'reOrder',
        MENU_ID: 390102
      },
      {
        name: '催办',
        icon: 'order_11.png',
        url: 'reminder',
        MENU_ID: 390103
      },
      {
        name: '待审核',
        icon: 'order_1.png',
        url: 'examineOrder',
        MENU_ID: 390104
      },
      {
        name: '录单',
        icon: 'order_19.png',
        url: 'createOrder',
        MENU_ID: 390105
      },
      {
        name: '抄表',
        icon: 'order_21.png',
        url: 'meter-control',
        MENU_ID: 390106
      },
      {
        name: '控阀',
        icon: 'order_20.png',
        url: 'valve-control',
        MENU_ID: 390107
      },
      {
        name: '已办结',
        icon: 'order_16.png',
        url: 'order-complete',
        MENU_ID: 390108
      },
      // {
      //   name: '待分派',
      //   icon: 'order_16.png',
      //   url: 'dispitchOrder',
      // },
      // {
      //   name: '待受理',
      //   icon: 'order_17.png',
      //   url: 'accept',
      // },
      // {
      //   name: '工单池',
      //   icon: 'order_14.png',
      //   url: 'orderPow',
      // },
    ],
    Menus: [],
    topMenu: [],
    menuSwiperHeight: 200,
    isRecording: false,
    audioPath: ''
  },
  onLoad() {
    this.checkUpdate();
    const that = this;
    that.data.timer = setInterval(function () {
      that.getWxOrderStatusCount();
      that.getAuditCount();
    }, 180000);
  },
  onShow() {
    this.getUserInfo();
    this.GetMiniAppMenu();
    this.getMsgList();
    this.getWxOrderStatusCount();
    this.getAuditCount();
    // wx.getLocation({
    //   type: 'gcj02',
    //   success(res) {
    //     const latitude = res.latitude
    //     const longitude = res.longitude
    //     wx.request({
    //       method: 'POST',
    //       url: `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=b7f457ec773d1ff7c0807a99ee5036dd&radius=1000&extensions=all`,
    //       success: function (res) {
    //         console.log(res.data);
    //       },
    //     })
    //   }
    // })
  },
  onHide() {
    clearInterval(this.data.timer);
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this.getUserInfo();
    this.getMsgList();
    this.getWxOrderStatusCount();
    this.getAuditCount();
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  checkUpdate() {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '小程序版本更新，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        });
      }
    } catch (e) {}
  },
  GetMiniAppMenu() {
    http.GetMiniAppMenu({
      ModuleID: 39
    }).then(res => {
      if (res.code === 200) {
        const menus = res.data.menu.filter(menu => menu.TYPE === 2);
        menus.sort((a, b) => a.SORT_NO - b.SORT_NO)
        const list = [];
        for (let i = 0; i < menus.length; i++) {
          const thisMenu = menus[i];
          const routeMenu = this.data.MenuRoutes.find(m => m.MENU_ID === thisMenu.MENU_ID);
          const icon = routeMenu ? routeMenu.icon : 'order_2.png';
          const url = routeMenu ? routeMenu.url : 'empty';
          list.push({
            name: thisMenu.TITLE,
            icon: icon,
            url: url,
          })
        }
        this.setData({
          Menus: list
        });
        this.getTopMenu();
      }
    })
  },
  getTopMenu() {
    const chunkedArrays = [];
    for (let i = 0; i < this.data.Menus.length; i += 8) {
      chunkedArrays.push(this.data.Menus.slice(i, i + 8));
    }
    this.setData({
      topMenu: chunkedArrays
    });
  },
  menuSwiperChange(e) {
    const current = e.detail.current;
    const swiperItem = this.data.topMenu[current];
    let h = 0;
    if (swiperItem.length >= 5) {
      h = 200;
    } else {
      h = 100;
    }
    this.setData({
      menuSwiperHeight: h
    });
  },
  toPage(e) {
    var data = e.currentTarget.dataset;
    if (data.url === 'empty') {
      wx.showToast({
        icon: 'none',
        title: '建设中',
        duration: config.toast.duration
      })
    } else {
      wx.navigateTo({
        url: "/subpage/" + data.url + '/' + data.url
      });
    }


  },
  noticeSwiperClick: function (e) {
    wx.navigateTo({
      url: "/subpage/notice/notice"
    });
  },
  getWxOrderStatusCount() {
    http.GetWxOrderStatusCount().then(res => {
      if (res.code === 200) {
        const MenuList = [...this.data.Menus];
        for (let i = 0; i < MenuList.length; i++) {
          const item = MenuList[i]
          if (item.name === '待执行') {
            item.Count = res.data.HandleCount;
          } else if (item.name === '二次派单') {
            item.Count = res.data.ReOrderCount;
          } else if (item.name === '催办') {
            item.Count = res.data.ReminderCount;
          }
          // else if (item.name === '工单池') {
          //   item.Count = res.data.OrderPoolCount;
          // } else if (item.name === '待分派') {
          //   item.Count = res.data.AssignCount;
          // }
        }
        this.getTopMenu();
      }
    });
  },
  getAuditCount() {
    let params = {
      pagination: {
        page: 1,
        rows: 9999,
        sidx: '',
        sord: ''
      },
      queryParam: {
        CommonParam: ''
      }
    };
    http.GetListAudit(params).then(res => {
      if (res.code === 200) {
        const MenuList = [...this.data.Menus]
        const menu = MenuList.find(item => item.name === '待审核')
        menu.Count = res.data.TotalCount;
        this.getTopMenu();
      }
    }).catch(_err => {});
  },
  getMsgList: function () {
    const params = {
      pagination: JSON.stringify({
        page: 1,
        rows: 10,
        sidx: 'sendTime',
        sord: 'desc'
      }),
      queryJson: JSON.stringify({
        msgType: "1,2",
        msgStatus: 0
      })
    };
    http.GetMsgList(params).then(res => {
      if (res.code === 200) {
        const multiple = res.data.Items.length > 1 ? 2 : 1;
        this.setData({
          msgList: res.data.Items,
          multiple: multiple
        })
      }
    })
  },
})